<template>
	<view class="container">
	  <!-- 固定头部区域：始终显示搜索框和栏目tab -->
		<view class="fixed-header">
			<!-- 标签筛选 -->
		<view class="flag-search">
		  <view class="flag-search-box">
				<text class="flag-search-icon">🏷️</text>
				<input 
				  type="text" 
				  placeholder="搜索标签" 
				  confirm-type="search" 
				  v-model="flagSearchText"
				  @confirm="searchByFlag" 
				  @input="onFlagInputChange"
				  style="flex:1;"
				/>
				<text v-if="flagSearchText" class="flag-search-clear" @tap="clearFlagSearch">✕</text>
			<!-- 查询按钮 -->
			<button size="mini" type="primary" class="search-btn" @tap="searchByFlag">查询</button>
				<text class="refresh-text" @tap="manualRefresh">刷新</text>
			  </view>
		  <!-- 渲染模式切换图标按钮，始终显示 -->
		  <view class="render-mode-container">
			<view @tap="toggleRenderMode" class="render-mode-toggle">
			  <template v-if="useTemplateRender">🖥️</template>
			  <template v-else>📄</template>
			</view>
				</view>
			  </view>
			<!-- 栏目tab -->
			<scroll-view scroll-x class="category-scroll" :show-scrollbar="false">
			  <view class="category-list">
				<view 
				  v-for="item in sortedCategories" 
				  :key="item.id"
				  class="category-item"
				  :class="{'category-item-active': currentCategory && currentCategory.id === item.id}"
				  @tap="switchCategory(item)"
				>
				  <text class="category-title">{{item.categoryTitle || item.typetitle}}</text>
				</view>
			  </view>
			</scroll-view>
		</view>
	  <!-- 占位，避免 fixed-header 遮挡内容 -->
	  <view class="header-placeholder"></view>
	  <!-- 模板渲染区/默认内容区（互斥） -->
	  <view class="main-content">
	    <rich-text v-if="useTemplateRender && renderedTemplate" :nodes="renderedTemplate" class="template-content"></rich-text>
	    <view v-else>
	      <!-- 只保留内容区和状态，不再重复头部 -->
		<scroll-view 
		  scroll-y 
		  class="content-scroll"
		  @scrolltolower="loadMore"
		  :refresher-enabled="true"
		  @refresherrefresh="onRefresh"
		  :refresher-triggered="isRefreshing"
		>
		  <view class="content-grid">
			<view 
	            v-for="item in articles" 
			  :key="item.id"
			  class="grid-item"
			  @tap="goDetail(item)"
			>
			  <view class="image-container">
				  <image 
					v-if="getFirstImage(item.litpic)"
					:src="getFirstImage(item.litpic)"
					mode="aspectFill"
					class="grid-image"
					@error="onImageError"
				  />
				  <view v-if="item.flag" class="flag-corner">
					<flag-tags :flags="item.flag"></flag-tags>
				  </view>
			  </view>
			  <view class="grid-info">
				<text class="grid-title">{{item.title}}</text>
				<text v-if="item.shorttitle" class="grid-subtitle">{{item.shorttitle}}</text>
				<view class="grid-tags">
	                <text v-if="item.tags && item.tags.length > 0" v-for="(tag, index) in item.tags" :key="index" class="tag">{{tag}}</text>
				  <text v-else-if="item.typetitle" class="tag">{{item.typetitle}}</text>
				</view>
				<text v-if="item.descrip" class="grid-desc">{{item.descrip}}</text>
				<view class="grid-meta">
				  <text class="meta-item">{{ formatDate(item.date || item.content_datetime || item.contentDatetime || item.createDate || item.updateDate) }}</text>
				  <text class="meta-item">浏览 {{item.hit || 0}}</text>
				  <text v-if="item.author" class="meta-item">作者：{{item.author}}</text>
				  <text v-if="item.source" class="meta-item">来源：{{item.source}}</text>
				</view>
			  </view>
			</view>
		  </view>
		  <!-- 加载更多 -->
		  <view v-if="loading" class="loading">
			<text class="loading-text">加载中...</text>
		  </view>
	        <view v-if="!hasMore && articles.length > 0" class="no-more">
			<text class="no-more-text">没有更多数据了</text>
		  </view>
		  <!-- 空状态 -->
	        <view v-if="!loading && articles.length === 0" class="empty-state">
			<text class="empty-text">暂无内容</text>
		  </view>
		</scroll-view>
		</view>
	  </view>
	</view>
  </template>
  
  <script>
  import { categoryApi, articleApi } from '@/api/config';
  import FlagTags from '@/components/FlagTags.vue';
  import config from '@/config';
  import { shareApi } from '@/api/config';
  import templateService from '@/utils/template';
  import Mustache from 'mustache';
  import { preprocessArticles } from '@/utils/templateData';
  import { formatDate } from '@/utils/date';
  export default {
	components: {
	  FlagTags
	},
	data() {
	  return {
		categories: [],
		articles: [],
		currentCategory: null,
		page: 1,
		size: 10,
		loading: false,
		hasMore: true,
		isRefreshing: false,
		searchText: '',
		error: '',
		totalPages: 1,       // 总页数
		selectedFlag: '',     // 当前选中的标签
		flagSearchText: '', // 标签搜索框的文本
		showFlagSuggestions: false, // 是否显示标签建议
		filteredFlags: [], // 过滤后的标签建议
		renderedTemplate: '', // 模板渲染内容，确保响应式
		useTemplateRender: false, // 默认使用普通样式
		listTemplate: '' // 列表模板内容
	  }
	},
	computed: {
	  sortedCategories() {
		// 只显示叶子节点（leaf: true），按 categorySort 降序
		return this.categories
		  .filter(item => item.leaf === true)
		  .sort((a, b) => {
			const sortA = parseInt(a.categorySort) || 0;
			const sortB = parseInt(b.categorySort) || 0;
			return sortB - sortA;
		});
	  }
	},
	onLoad() {
	  this.loadPageData();
	  
	  // 监听登录状态变化
	  uni.$on('loginSuccess', () => {
		this.loadPageData();
	  });
	},
	onShow() {

	  if (this.articles.length === 0 && this.categories.length === 0) {
		this.loadPageData();
	  } else {
	  this.refreshData();
	  }
	},
	// 添加页面激活事件，确保从其他页面返回时数据是最新的
	onActivated() {
	  this.refreshData();
	},
	// 监听页面显示时的登录状态
	onReady() {
	  // 检查登录状态，如果已登录但数据为空，则重新加载
	  const userInfo = uni.getStorageSync('userInfo');
	  if (userInfo && this.articles.length === 0) {
		this.loadPageData();
	  }
	},
	// 页面卸载时清理事件监听器
	onUnload() {
	  uni.$off('loginSuccess');
	},
	methods: {
	  async loadPageData() {
		try {
		  this.loading = true;
		  this.error = '';
		  
		  // 重置所有状态
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.selectedFlag = '';
		  this.flagSearchText = '';
		  this.showFlagSuggestions = false;
		  
		  // 1. 获取分类数据
		  const categoryRes = await categoryApi.getList();

		  console.log("获取的分类数据"+JSON.stringify(categoryRes));
		  
		  if (categoryRes.code === 200) {
			this.categories = categoryRes.data.rows || [];
			
			// 遍历所有叶子分类，打印模板内容
			for (const cat of this.categories) {
			  if (cat.leaf === true) {
				// 打印列表模板内容
				templateService.getCategoryListTemplate(cat).then(listTpl => {
				});
				// 打印详情模板内容
				templateService.getCategoryDetailTemplate(cat).then(detailTpl => {
				});
			  }
			}
			
			if (this.sortedCategories.length > 0) {
			  this.currentCategory = this.sortedCategories[0];
			} else {
			  console.warn("没有找到可用的分类");
			}
		  } else {
			console.error("分类数据加载失败:", categoryRes);
		  }
		  
		  // 2. 获取文章数据
		  if (this.currentCategory) {
		  await this.loadArticles();
			// 不再初始化时请求模板内容
		  } else {
			console.warn("没有选中分类，跳过文章加载");
		  }
		  
		} catch (error) {
		  this.error = error.message || '页面加载失败';
		  console.error('页面加载失败:', error);
		} finally {
		  this.loading = false;
		}
	  },
	  
	  async loadArticles(isLoadMore = false) {
		if (this.loading && !isLoadMore) return;
		
		try {
		  if (!isLoadMore) {
			this.loading = true;
		  }
		  
		  let res;
		  if (this.selectedFlag) {
			// 标签查询时，调用 /cms/content/tag-list
			res = await articleApi.getListByTag({
			  tag: this.selectedFlag,
			  pageNo: this.page,
			  size: this.size
			});
			// 适配字段
			if (res.code === 200 && Array.isArray(res.data)) {
			  res.data = res.data.map(item => ({
				id: item.id,
				title: item.contentTitle,
				descrip: item.contentDescription,
				litpic: item.contentImg,
				date: item.contentDatetime,
				flag: item.contentType ? item.contentType.split(',') : [],
				tags: item.contentType ? item.contentType.split(',') : []
			  }));
			}
			// 标签查询结果可能来自多个栏目，取消栏目选中状态
			this.currentCategory = null;
		  } else {
			const params = {
			  categoryId: this.currentCategory?.id,
			  pageNo: this.page,
			  size: this.size,
			  keyword: this.searchText
			};
			res = await articleApi.getList(params);
		  }
		  
		  if (res.code === 200) {
			const list = res.data.rows || res.data || [];
			const total = res.data.total || list.length || 0;
			this.totalPages = Math.ceil(total / this.size) || 1;
			
			
			// 根据当前分类筛选文章
			const filteredList = this.filterArticlesByCategory(list);
			
			// 模板渲染相关打印：preprocessArticles 处理后的 articles 数据
			const processedArticles = preprocessArticles(isLoadMore ? [...this.articles, ...filteredList] : filteredList);
			
			this.articles = processedArticles;
			this.hasMore = filteredList.length === this.size;
			
			// 统计文章中的标签
			this.collectFlags();
		  }
		} catch (error) {
		  if (!isLoadMore) {
			this.error = error.message || '文章加载失败';
		  }
		  console.error('加载文章失败:', error);
		} finally {
		  this.loading = false;
		  if (this.isRefreshing) {
			this.isRefreshing = false;
		  }
		}
	  },
	  
	  // 收集所有文章中的标签
	  collectFlags() {
		const flags = new Set();
		this.articles.forEach(article => {
		  if (article.flag && Array.isArray(article.flag)) {
			article.flag.forEach(flag => {
			  flags.add(flag);
			});
		  }
		});
		
		// 更新标签选项
		if (flags.size > 0) {
		  this.flagOptions = Array.from(flags);
		}
	  },
	  
	  // 根据标签筛选文章
	  async filterByFlag(flag) {
		// 如果选择的是相同标签，则取消筛选
		if (this.selectedFlag === flag) {
		  this.selectedFlag = '';
		} else {
		  this.selectedFlag = flag;
		}
		
		// 重置页码并重新加载文章
		this.page = 1;
		this.hasMore = true;
		this.articles = [];
		await this.loadArticles();
	  },
	  
	  // 根据当前分类筛选文章
	  filterArticlesByCategory(articles) {
		if (!this.currentCategory || !articles || articles.length === 0) {
		  return articles;
		}
		
		const currentCategoryTitle = this.currentCategory.categoryTitle || this.currentCategory.typetitle;
		if (!currentCategoryTitle) {
		  return articles;
		}
		
		const filteredArticles = articles.filter(article => {
		  const articleTypeTitle = article.typetitle;
		  const isMatch = articleTypeTitle === currentCategoryTitle;
		  return isMatch;
		});
		
		return filteredArticles;
	  },
	  
	  async switchCategory(category) {
		try {
		  this.currentCategory = category;
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.selectedFlag = ''; // 切换分类时重置标签筛选
		  
		  await this.loadArticles();
		  await this.loadTemplate(this.currentCategory); // 强制模板渲染
		} catch (error) {
		  uni.showToast({
			title: '切换分类失败',
			icon: 'none'
		  });
		  console.error('切换分类失败:', error);
		}
	  },
	  
	  async onSearch(e) {
		try {
		  this.searchText = e.detail.value;
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.selectedFlag = ''; // 搜索时重置标签筛选
		  await this.loadArticles();
		} catch (error) {
		  console.error('搜索失败:', error);
		}
	  },
	  
	  async loadMore() {
		if (this.hasMore && !this.loading) {
		  this.page++;
		  await this.loadArticles(true);
		}
	  },
	  
	  async onRefresh() {
		this.isRefreshing = true;
		this.page = 1;
		this.hasMore = true;
		// 不重置标签搜索，保留当前筛选条件
		await this.loadArticles();
	  },
	  
	  async refreshData() {
		try {
		  
		  // 1. 刷新分类数据
		  const categoryRes = await categoryApi.getList();
		  
		  if (categoryRes.code === 200) {
			this.categories = categoryRes.data.rows || [];

			// 如果当前没有选中分类，选择第一个
			if (!this.currentCategory && this.sortedCategories.length > 0) {
			  this.currentCategory = this.sortedCategories[0];
			}
		  } else {
			console.error('分类数据刷新失败:', categoryRes);
		  }
		  
		  // 2. 刷新文章数据
		  if (this.currentCategory) {
			await this.loadArticles();
		  } else {
			console.warn('没有选中分类，跳过文章刷新');
		  }
		  		  
		} catch (error) {
		  console.error('刷新数据失败:', error);
		}
	  },
	  
	  retry() {
		this.error = '';
		this.loadPageData();
	  },
	  
	  goDetail(item) {
		// 获取当前栏目的详情模板，并传递给详情页
		let detailTemplate = '';
		if (this.currentCategory && this.currentCategory.categoryUrl) {
		  // 如果已经加载过详情模板，直接使用
		  templateService.getCategoryDetailTemplate(this.currentCategory).then(tpl => {
			console.log('[首页] 传递详情模板到详情页，模板长度:', tpl ? tpl.length : 0);
			// 将模板和栏目信息传递给详情页
			uni.navigateTo({
			  url: `/pages/detail/detail?id=${item.id}&categoryId=${this.currentCategory.id}`
			});
		  }).catch(err => {
			console.error('[首页] 获取详情模板失败:', err);
			// 失败时也跳转，但不传递模板
			uni.navigateTo({
			  url: `/pages/detail/detail?id=${item.id}&categoryId=${this.currentCategory.id}`
			});
		  });
		} else {
		  // 没有当前栏目，直接跳转
		  uni.navigateTo({
			url: `/pages/detail/detail?id=${item.id}`
		  });
		}
	  },
	  
	  getFirstImage(images) {
		if (!images) return '';
		try {
		  // 空数组字符串直接返回空
		  if (typeof images === 'string' && images.trim() === '[]') return '';
		  let imageList = images;
		  if (typeof images === 'string') {
			const cleanStr = images.replace(/\\/g, '');
			imageList = JSON.parse(cleanStr);
		  }
		  if (Array.isArray(imageList) && imageList.length > 0) {
			const firstImage = imageList[0];
			let imageUrl = '';
			if (typeof firstImage === 'object' && firstImage.url) {
			  imageUrl = firstImage.url;
			} else if (typeof firstImage === 'string') {
			  imageUrl = firstImage;
			}
			if (imageUrl) {
			  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
				return imageUrl;
			  }
			  return `http://localhost:8080${imageUrl}`;
			}
		  }
		  return '';
		} catch (error) {
		  return '';
		}
	  },
	  
	  formatDate(dateStr) {
		if (!dateStr) return '';
		try {
		  return formatDate(dateStr);
		} catch (error) {
		  return dateStr;
		}
	  },
	  
	  onImageError(e) {
		// 可设置默认图片
	  },
	  

	  // 标签搜索相关方法
	  onFlagInputChange(e) {
		this.showFlagSuggestions = true;
		this.filteredFlags = this.flagOptions.filter(flag => 
		  flag.toLowerCase().includes(e.detail.value.toLowerCase())
		);
	  },

	  searchByFlag() {
		const searchValue = this.flagSearchText.trim();
		if (searchValue) {
		  this.selectedFlag = searchValue;
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.showFlagSuggestions = false; // 关闭建议
		  // 查询时清空输入框
		  this.flagSearchText = '';
		  this.loadArticles(); // 只在点击查询时请求
		} else {
		  // 如果输入为空，恢复全部
		  this.selectedFlag = '';
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.loadArticles();
		}
	  },

	  clearFlagSearch() {
		this.flagSearchText = '';
		this.showFlagSuggestions = false;
		this.selectedFlag = '';
		this.page = 1;
		this.hasMore = true;
		this.articles = [];
		this.loadArticles();
	  },

	  selectFlag(flag) {
		this.selectedFlag = flag;
		this.showFlagSuggestions = false;
		this.flagSearchText = '';
		this.page = 1;
		this.hasMore = true;
		this.articles = [];
		this.loadArticles();
	  },

	  // 手动刷新数据
	  async manualRefresh() {
		uni.showLoading({
		  title: '刷新中...'
		});
		
		try {
		  
		  // 重置所有状态
		  this.page = 1;
		  this.hasMore = true;
		  this.articles = [];
		  this.selectedFlag = ''; // 重置标签筛选
		  this.flagSearchText = ''; // 清空搜索框
		  this.showFlagSuggestions = false; // 关闭建议
		  
		  // 执行完整的数据刷新
		  await this.refreshData();
		  
		  uni.showToast({
			title: '刷新成功',
			icon: 'success'
		  });
		} catch (error) {
		  console.error('手动刷新失败:', error);
		  uni.showToast({
			title: '刷新失败',
			icon: 'none'
		  });
		} finally {
		  uni.hideLoading();
		}
	  },

	  onShareAppMessage() {
		// 仿照详情页，动态生成栏目分享token
		const defaultTitle = this.currentCategory?.categoryTitle || this.currentCategory?.typetitle || '栏目分享';
		const defaultPath = `/pages/index/index`;
		const defaultImage = config.share?.defaultImage || '';
		const promise = new Promise(async (resolve) => {
		  if (!this.currentCategory || !this.currentCategory.id) {
			resolve({
			  title: defaultTitle,
			  path: defaultPath,
			  imageUrl: defaultImage
			});
			return;
		  }
		  try {
			const res = await shareApi.create({
			  shareType: 'category',
			  targetId: this.currentCategory.id,
			  shareTitle: this.currentCategory.categoryTitle || this.currentCategory.typetitle,
			  shareDescription: this.currentCategory.description || '',
			});
			if (res.code === 200 && res.data && res.data.shareToken) {
			  resolve({
				title: res.data.shareTitle,
				path: `/pages/shared/category?token=${res.data.shareToken}`,
				imageUrl: defaultImage
			  });
			} else {
			  resolve({
				title: defaultTitle,
				path: defaultPath,
				imageUrl: defaultImage
			  });
			}
		  } catch (e) {
			resolve({
			  title: defaultTitle,
			  path: defaultPath,
			  imageUrl: defaultImage
			});
		  }
		});
		return {
		  title: defaultTitle,
		  path: defaultPath,
		  imageUrl: defaultImage,
		  promise
		};
	  },
	  onShareTimeline() {
		const defaultTitle = this.currentCategory?.categoryTitle || this.currentCategory?.typetitle || '栏目分享';
		const defaultImage = config.share?.defaultImage || '';
		return {
		  title: defaultTitle,
		  query: '',
		  imageUrl: defaultImage
		};
	  },
	  async loadTemplate(category) {
		this.listTemplate = await templateService.getCategoryListTemplate(category);
		if (!this.listTemplate) {
		  uni.showToast({ title: '未配置模板，已切换为默认样式', icon: 'none' });
		  this.useTemplateRender = false;
		  return;
		}
		this.renderTemplate();
	  },
	  renderTemplate() {
		if (!this.listTemplate) {
		  this.renderedTemplate = '';
		  return;
		}
		// 打印所有 articles 的图片字段
		if (Array.isArray(this.articles)) {
		  this.articles.forEach((a, idx) => {
		  });
		}
		// 扁平化数据结构，便于 mustache 渲染
		const templateData = {
		  ...(this.currentCategory || {}),
		  articles: this.articles
		};
		let rendered = templateService.parseTemplate(this.listTemplate, templateData);

		// 还原所有 / 被转义的情况，拼接成标准 http 链接
		rendered = rendered.replace(/http:&#x2F;&#x2F;/g, 'http://');
		rendered = rendered.replace(/https:&#x2F;&#x2F;/g, 'https://');
		rendered = rendered.replace(/&#x2F;/g, '/');

		// 新增：单独打印所有 <img src=...> 片段
		const imgSrcMatches = rendered.match(/<img\s+[^>]*src=["'][^"']+["'][^>]*>/gi);
		if (imgSrcMatches) {
		  imgSrcMatches.forEach((imgTag, idx) => {
			const srcMatch = imgTag.match(/src=["']([^"']+)["']/i);
		  });
		}
		this.renderedTemplate = rendered;
		// 已删除 document.querySelector 相关代码
	  },
	  toggleRenderMode() {
		this.useTemplateRender = !this.useTemplateRender;
		
		if (this.useTemplateRender) {
		  // 切换到模板渲染模式，尝试渲染模板
		  if (this.listTemplate) {
			this.renderTemplate();
			uni.showToast({ title: '已切换为模板样式', icon: 'none' });
		  } else {
			// 如果没有模板，重新请求一次
			this.loadTemplate(this.currentCategory, true);
		  }
		} else {
		  // 切换到默认渲染模式
		  uni.showToast({ title: '已切换为默认样式', icon: 'none' });
		}
		
		// 切换后重新加载一次数据
		this.page = 1;
		this.hasMore = true;
		this.loadArticles();
	  }
	}
  }
  </script>
  
  <style lang="scss" scoped>
  .container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
	position: relative;
  }
  
  /* 固定头部区域 */
  .fixed-header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	background-color: #fff;
	box-shadow: 0 2px 6px rgba(0,0,0,0.06);
  }
  
  /* 头部占位，防止内容被遮挡 */
  .header-placeholder {
	height: 92px; /* 进一步减小占位高度 */
  }
  
  /* 标签筛选样式 */
  .flag-search {
	padding: calc(var(--status-bar-height) - 15px) 12px 2px; /* 减小底部边距 */
	background-color: #fff;
	display: flex;
	align-items: center;
	
	.flag-search-box {
	  flex: 1;
	  display: flex;
	  align-items: center;
	  background-color: #f5f5f5;
	  border-radius: 16px; /* 稍微减小圆角 */
	  padding: 0px 5px;
	  height: 30px; /* 固定高度 */
	  
	  .flag-search-icon {
		font-size: 12px;
		margin-right: 6px;
		color: #666;
	  }
	  
	  input {
		flex: 1;
		font-size: 14px;
		padding-right: 6px;
		height: 24px;
		line-height: 24px;
		background-color: transparent;
	  }
	  
	  .flag-search-clear {
		font-size: 16px; /* 调整清除按钮大小 */
		color: #999;
		padding: 0 4px;
	  }
	  
	  .refresh-text {
		font-size: 13px;
		color: #2196f3;
		padding: 0 5px 0 8px;
		border-left: 1px solid #ddd;
		font-weight: 500;
	  }

	  .search-btn {
		margin-left: 6px;
		border-radius: 14px;
		font-size: 13px;
		padding: 0 10px;
		background-color: #2196f3;
		border: none;
		height: 24px; /* 减小按钮高度 */
		line-height: 24px;
		box-shadow: 0 2px 4px rgba(33, 150, 243, 0.2);
		transition: all 0.2s ease;

		&:active {
		  transform: scale(0.95);
		  box-shadow: 0 1px 2px rgba(33, 150, 243, 0.1);
		}
	  }
	}
	
	.render-mode-container {
	  margin-left: 8px;
	}

	.render-mode-toggle {
	  font-size: 18px; /* 调整图标大小 */
	  color: #2196f3;
	  padding: 3px;
	  cursor: pointer;
	  background-color: rgba(33, 150, 243, 0.1);
	  border-radius: 50%;
	  width: 30px; /* 调整为与搜索框相同高度 */
	  height: 30px;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  transition: all 0.2s ease;

	  &:active {
		transform: scale(0.9);
		background-color: rgba(33, 150, 243, 0.2);
	  }
	}

	.flag-suggestions {
	  position: absolute;
	  top: calc(var(--status-bar-height) + 40px);
	  left: 15px;
	  right: 15px;
	  background-color: #fff;
	  border-radius: 8px;
	  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	  z-index: 101;
	  max-height: 200px;
	  overflow-y: auto;
	  display: flex;
	  flex-direction: column;
	  gap: 5px;
	  padding: 5px 0;
	}

	.flag-suggestion-item {
	  display: flex;
	  align-items: center;
	  padding: 8px 12px;
	  gap: 8px;
	  border-radius: 6px;
	  cursor: pointer;
	  
	  &:active {
		background-color: #f0f0f0;
	  }
	}

	.flag-suggestion-text {
	  font-size: 14px;
	  color: #333;
	}
  }
  
  .category-scroll {
	background-color: #fff;
	white-space: nowrap;
	border-bottom: 1px solid #eee;
	padding: 0 0 3px; /* 减小上下边距 */
	
	.category-list {
	  display: inline-flex;
	  padding: 0 5px;
	}
	
	.category-item {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  padding: 4px 5px; /* 减小上下边距 */
	  font-size: 14px;
	  color: #666;
	  position: relative;
	  
	  &-active {
		color: #2196f3;
		font-weight: 500;
		
		&::after {
		  content: '';
		  position: absolute;
		  bottom: -1px;
		  left: 50%;
		  transform: translateX(-50%);
		  width: 24px;
		  height: 3px;
		  background-color: #2196f3;
		  border-radius: 1.5px;
		}
	  }
	  
	  .category-title {
		font-size: 14px;
		color: inherit;
		text-align: center;
		margin-top: 0;
	  }
	}
  }
  
  .content-scroll {
	height: calc(100vh - 92px); /* 减去头部高度 */
	box-sizing: border-box;
  }
  
  /* 调整内容区域的上边距，确保不被栏目遮挡 */
  .content-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 8px; /* 减小间距 */
	padding: 8px; /* 减小内边距 */
	margin-top: 2px; /* 减小顶部边距 */
}

/* 确保模板内容也有足够的上边距 */
.template-content {
	padding-top: 2px; /* 减小顶部边距 */
	box-sizing: border-box;
	min-height: calc(100vh - 92px);
}

/* 调整图片容器样式，确保不被遮挡 */
.grid-item {
	background: #fff;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
	display: flex;
	flex-direction: column;
	transition: transform 0.2s ease;
	margin-bottom: 0; /* 移除底部边距 */
}

/* 确保图片填充容器 */
.grid-item .image-container {
	width: 100%;
	height: 140px; /* 减小图片高度 */
	overflow: hidden;
	position: relative;
}

/* 确保图片填充容器 */
.grid-item .image-container .grid-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-top-left-radius: 12px;
	border-top-right-radius: 12px;
}
  
  .loading, .no-more, .empty-state {
	padding: 12px 0;
	text-align: center;
  }
  
  .loading-text, .no-more-text, .empty-text {
	font-size: 14px;
	color: #999;
  }
  
  .error-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100vh;
	padding: 20px;
  }
  
  .error-text {
	font-size: 16px;
	color: #666;
	margin-bottom: 20px;
	text-align: center;
  }
  
  .retry-btn {
	padding: 12px 24px;
	background-color: #007aff;
	color: #fff;
	border-radius: 6px;
	font-size: 16px;
  }
  </style>